<?php
if( !defined('IN_INDEX') )
{
	printError("ACCESS DENIED", "This page is hidden.");
	exit;
}

/*******************************************************************
** checkSession()
**	Checks if a user is logged in.
** RETURN VALUES
**	true - User is logged in
**	false - User is not logged in (default)
*******************************************************************/
function checkSession()
{
	//global $_SESSION;
	global $SESSION_NAME;
	global $db;
	global $USER;
	if(isset($USER))
	{
		$user_id = $USER->getId();
	}
	else
	{
		$user_id = 0;
	}
	$user_ip = getVisitorIp();
	$current_page = $_SERVER['REQUEST_URI'];
	if(isset($_SESSION['user_id']))
	{
		$sql = "SELECT * FROM sessions WHERE session_id='" . session_id() . "' OR session_user_id= '". $user_id ."'";
		if(!$result = $db->sql_query($sql))
		{
			printError("SQL ERROR", mysql_error($sql));
		}
		else
		{
			if($db->sql_affectedrows() > 1)
			{
			$sql2 = "DELETE FROM sessions WHERE session_user_id='" . $user_id . "' ";
			}
			
			elseif($db->sql_affectedrows() > 0)
			{
				$sql2 = "UPDATE sessions SET ".
				"session_last_visit='" . time() . "', ".
				"session_user_id='" . $user_id . "', ".
				"session_page='" . $current_page . "'".
				"WHERE session_id='" . session_id() . "'";
			}
			
			else
			{
				$sql2 = "INSERT INTO sessions SET ".
				"session_id='" . session_id() . "', ".
				"session_user_id='" . $user_id . "', ".
				"session_last_visit='" . time() . "', ".
				"session_start='" . time() . "', ".
				"session_ip='" . $user_ip . "', ".
				"session_page='" . $current_page . "'";
			}
			
			if(!$result2 = $db->sql_query($sql2))
			{
				printError("SQL ERROR", mysql_error($sql2));
			}
		}
		
		return true;
	}
	return false;
}
/** checkSession() END **/

/*******************************************************************
** user_checkLogin($email, $pass)
**	Checks input values for existance in user database and compare
**	the password.
** RETURN VALUES
**	0 - Missmatch email/password (default)
**	1 - Account is disabled/not activated
**	2 - Successfull login
*******************************************************************/
function user_checkLogin($email, $pass)
{
	global $db;
	
	$sql = "SELECT user_email, user_password, user_rank FROM " . USERS_TABLE . " ".
	"WHERE user_email='" . $email . "'";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		if( $row = $db->sql_fetchrow($result) )
		{
			if($row['user_rank'] > 0)
			{
				if(strcmp(cryptString($pass), $row['user_password']) == 0)
				{
					$sql2 = "INSERT INTO sessions SET ".
					"session_id='" . session_id() . "', ".
					"session_user_id='" . $user_id . "', ".
					"session_last_visit='" . time() . "', ".
					"session_start='" . time() . "', ".
					"session_ip='" . $user_ip . "', ".
					"session_page='" . $current_page . "'";
					if(!$result2 = $db->sql_query($sql2))
					{
						printError("SQL ERROR", mysql_error($sql2));
					}
					$sql3 = "UPDATE users SET user_login_count = user_login_count+1 WHERE user_email='".$email."'";
					if(!$result3 = $db->sql_query($sql3))
					{
						printError("SQL ERROR", mysql_error($sql3));
					}
					return 2;
				}
			}
			else
			{
				$sql3 = "UPDATE users SET user_login_count = user_login_count+1 WHERE user_email='".$email."'";
				if(!$result3 = $db->sql_query($sql3))
				{
					printError("SQL ERROR", mysql_error($sql3));
				}
				return 1;
			}
		}
	}
	return 0;
}
/** user_checkLogin() END **/

/*******************************************************************
** countUsers()
**	Counts how many users are registered in the database
** RETURN VALUES
**	0 - Default value/No user registered (default)
**		-	The number of users in database
*******************************************************************/
function countUsers()
{
	global $db;
	
	$sql = "SELECT * FROM " . USERS_TABLE;
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}
/** countUsers() END **/

/*******************************************************************
** countTrainings()
*******************************************************************/
function countTrainings()
{
	global $db;
	
	$sql = "SELECT * FROM " . TRAINING_TABLE;
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}
/** countTrainings() END **/

/*******************************************************************
** checkUserExistance($email)
**	Checks if a user exists with the input email. Used for checking
**	for double registered emails and before trying to send an email
**	to the email address.
** RETURN VALUES
**	true - The email exist in user database
**	false	-	The doesn't exist in user database (default)
*******************************************************************/
function checkUserExistance($cmd, $input)
{
	global $db;
	
	if($cmd = "email")
	{
		$sql = "SELECT user_email FROM " . USERS_TABLE . " WHERE user_email='" . $input . "'";
	}
	elseif($cmd = "id")
	{
		$sql = "SELECT user_id FROM " . USERS_TABLE . " WHERE user_id='" . $input . "'";
	}
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		if($db->sql_affectedrows() > 0)
		{
			return true;
		}
	}
	return false;
}
/** checkUserExistance() END **/


function getNameFromId($input)
{
	global $db;
	
	$sql = "SELECT user_firstname, user_lastname FROM " . USERS_TABLE . " ".
	"WHERE user_id='" . $input . "'";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		if( $row = $db->sql_fetchrow($result) )
		{
			return $row['user_firstname'] . " " . $row['user_lastname'];
		}
	}
	return "";
}

function fetch_friends($id)
{
	global $db;
	$array = array();
	$array2 = array();
	$array_uid = array();
	$final_array = array();
	
	$sql = "SELECT * FROM user_friends WHERE user_id='" . $id . "' OR friend_user_id='" . $id . "'";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		while( $row = $db->sql_fetchrow($result) )
		{
			$id1 = $row['user_id'];
			$id2 = $row['friend_user_id'];
			
			if($id1 == $id)
			{
				$friend_id = $id2;
			}
			else
			{
				$friend_id = $id1;
			}
			
			$array[] = array(
				'id' => $row['friend_id'],
				'user_id' => $id,
				'friend_id' => $friend_id,
				'time' => $row['friend_time'],
				'status' => $row['friend_status'],
				'sender_id' => $row['user_id']
			);
		}
	}
	
	if(count($array) > 0)
	{
		$sql = "SELECT * FROM users WHERE";
		foreach($array as $k => $v)
		{
			if($k == 0)
			{
				$sql .= " user_id='" . $v['friend_id'] . "'";
			}
			else
			{
				$sql .= " OR user_id='" . $v['friend_id'] . "'";
			}
		}
		if(!$result = $db->sql_query($sql))
		{
			printError("SQL ERROR", mysql_error($sql));
		}
		else
		{
			while( $row = $db->sql_fetchrow($result) )
			{
				$array2 = array(
					'friend_id' => $row['user_id'],
					'firstname' => $row['user_firstname'],
					'lastname' => $row['user_lastname'],
					'last_visit' => $row['user_lastlogin'],
				);
				
				$array_uid[$row['user_id']] = $array2;
			}
		}
	}
	
	foreach($array as $k => $v)
	{
		if(!empty($array_uid[$v['friend_id']]))
		{
			$final_array[] = array(
				'id' => $v['id'],
				'user_id' => $v['friend_id'],
				'sender_id' => $v['sender_id'],
				'time' => $v['time'],
				'status' => $v['status'],
				'firstname' => $array_uid[$v['friend_id']]['firstname'],
				'lastname' => $array_uid[$v['friend_id']]['lastname'],
				'last_visit' => $array_uid[$v['friend_id']]['last_visit']
			);
		}
	}
	
	return $final_array;
}

function getActiveUsersTopList()
{
	global $db;
	
	$sql = "SELECT * FROM users WHERE user_posts >= 1 ORDER BY user_posts DESC LIMIT 40";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error());
	}
	echo "<table>";
	$i=1;
	while($row = mysql_fetch_array($result))
		{	
			$title = translate('visit_blog')." " . $row['user_firstname'] . " " . $row['user_lastname'] . ", ". translate(ucf(getCountryName($row['user_country'])) )." (" . translate('joindate') . " " . date("d.m.Y", $row['user_joined']) . ")";		
			echo "
			<tr>
            <td>". $i++ .".</td>
			<td>
				<a style='color:#555555; font-weight:bold;' href='index.php?action=profile&amp;id=". $row['user_id'] ."' title='". $title ."'>
				<div style='float: left; clear: right; padding-right: 3px;'><img src='img/flags/16/" . strtolower($row['user_country']). ".png' alt=" . $row['user_country'] ." /></div>
				". $row['user_firstname'] . " " . $row['user_lastname'] ."</a> (". $row['user_posts'] .")
			</td>
            </tr>";
		}
	echo "</table>";
	echo "<span style='font-size: 9px;'>". translate('toplist_active') ."</span>";
}

function getRandomUsersList()
{
	global $db;
	
	$sql = "SELECT * FROM users ORDER BY RAND() DESC LIMIT 40";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error());
	}
	echo "<table>";
	$i=1;
	while($row = mysql_fetch_array($result))
		{	
			$title = translate('visit_blog')." " . $row['user_firstname'] . " " . $row['user_lastname'] . ", ". translate(ucf(getCountryName($row['user_country'])) )." (" . translate('joindate') . " " . date("d.m.Y", $row['user_joined']) . ")";			
			echo "
			<tr>
            <td>". $i++ .".</td>
			<td>
				<a style='color:#555555; font-weight:bold;' href='index.php?action=profile&amp;id=". $row['user_id'] ."' title='". $title ."'>
				<div style='float: left; clear: right; padding-right: 3px;'><img src='img/flags/16/" . strtolower($row['user_country']). ".png' alt=" . $row['user_country'] ." /></div>
				". $row['user_firstname'] . " " . $row['user_lastname'] ."</a>
			</td>
            </tr>";
		}
	echo "</table>";
	echo "<span style='font-size: 9px;'>". translate('toplist_random') ."</span>";
}

function getMostReadUsersList()
{
	global $db;
	
	$sql = "SELECT 
	   users.user_id
     , users.user_firstname
     , users.user_lastname
     , users.user_country
     , users.user_joined
     , (SELECT count(counter.page) 
           FROM counter
          WHERE counter.category='user_profile' AND counter.page=users.user_id 
         )
     + (SELECT count(counter.page)
           FROM counter, training
          WHERE counter.category='post' AND counter.page=training.training_id AND training.user_id=users.user_id
         ) AS result
  FROM users
  ORDER BY result DESC
  LIMIT 40";
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error());
	}
	echo "<table>";
	$i=1;
	while($row = mysql_fetch_array($result))
		{		
			$visits = $row['result'];
			$title = translate('visit_blog')." " . $row['user_firstname'] . " " . $row['user_lastname'] . ", ". translate(ucf(getCountryName($row['user_country'])) )." (" . translate('joindate') . " " . date("d.m.Y", $row['user_joined']) . ")";
			echo "
			<tr>
            <td>". $i++ .".</td>
			<td>
				<a style='color:#555555; font-weight:bold;' href='index.php?action=profile&amp;id=". $row['user_id'] ."' title='". $title ."'>
				<div style='float: left; clear: right; padding-right: 3px;'><img src='img/flags/16/" . strtolower($row['user_country']). ".png' alt=" . $row['user_country'] ." /></div>
				". $row['user_firstname'] . " " . $row['user_lastname'] ."</a> (". $visits .")
			</td>
            </tr>";
		}
	echo "</table>";
	echo "<span style='font-size: 9px;'>". translate('toplist_visit') ."</span>";
}
	
function countFriendPending($id)
{
	global $db;
	
	$sql = "SELECT * FROM " . FRIENDS_TABLE . " WHERE friend_user_id='" . $id . "' AND friend_status='pending'";
	
	if(!$result = $db->sql_query($sql))
	{
		printerror("SQL ERROR", mysql_error());
	}
	else
	{
		return $db->sql_affectedrows();
	}
	
	return 0;
}

function checkFriendAccepted($friend_check, $user_id)
{
	global $db;
	
	$sql = "SELECT friend_status FROM " . FRIENDS_TABLE . " WHERE (user_id='" . $user_id . "' AND friend_user_id='" . $friend_check . "') OR (user_id='" . $friend_check . "' AND friend_user_id= '". $user_id ."') ";
	
	if(!$result = $db->sql_query($sql))
	{
		printerror("SQL ERROR", mysql_error());
	}
	else
	{
		while($row = $db->sql_fetchrow($result))
		{
			$checkfriend = $row['friend_status'];
		}
	}
	return $checkfriend;
}

function is_user_online($id)
{
	global $db;
	global $CONFIG;
	$array = array();
	
	$sql = "SELECT * FROM sessions WHERE session_user_id='" . $id . "' AND session_last_visit > " . (time() - $CONFIG['session_timeout']);
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		if($db->sql_affectedrows($result) > 0)
		{
			$row = $db->sql_fetchrow($result);
			$array = array(
				'last_visit' => $row['session_last_visit'],
				'page' => $row['session_page']
			);
			return $array;
		}
	}
	return array('last_visit' => 0, 'page' => '');
}

/*******************************************************************
** Function to delete a user from the system
** Deletes the user, post & comments.
*******************************************************************/

function deleteUser($id)
{
	global $db;
	global $CONFIG;
	
	$sql = "DELETE FROM " . USERS_TABLE . " WHERE user_id='". $id ."'";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
}
function deleteAllCommentByUserId($id)
{
	global $db;
	global $CONFIG;
	
	$sql="DELETE FROM " . COMMENTS_TABLE . " WHERE user_id = '". $id ."'";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
}
function deleteAllCommentsInBlog($id)
{
	global $db;
	global $CONFIG;
	
	$sql="DELETE FROM " . COMMENTS_TABLE . " WHERE comment_owner = '". $id ."'";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
}
function deleteAllLiftsFromUser($id)
{
	global $db;
	global $CONFIG;
	$values=array();
	
	$sql="SELECT training_id FROM " . TRAINING_TABLE . " WHERE user_id = '". $id ."'";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	
	while($row = mysql_fetch_array($result))
	{
			$values[] = $row['training_id'];
	}
	
	foreach($values as $k => $v)
	{
		$sql2="DELETE FROM " . LIFT_TABLE . " WHERE training_id = '". $v ."'";
		if(!$result2 = $db->sql_query($sql2))
		{
			printError('SQL_ERROR', mysql_error($sql2));
		}
	}
}
function deleteAllTrainingsByUserId($id)
{
	global $db;
	global $CONFIG;
	
	$sql="DELETE FROM " . TRAINING_TABLE . " WHERE user_id = '". $id ."'";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
}
function deleteAllFriendsByUserId($id)
{
	global $db;
	global $CONFIG;
	
	$sql="DELETE FROM " . FRIENDS_TABLE . " WHERE user_id = '". $id ."'";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
}
function removeProfilePic($id)
{
	global $db;
	global $CONFIG;
	
	$sql="UPDATE " . USERS_TABLE . " SET user_avatarPath='' WHERE user_id = '". $id ."'";
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
}
/*******************************************************************
** End user delete
*******************************************************************/

/*******************************************************************
** countSets() Total
*******************************************************************/
function countSets()
{
	global $db;
	
	$sql = "SELECT * FROM " . LIFT_TABLE;
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}
/** countSets() END **/
/*******************************************************************
** countSetsUser() From user
*******************************************************************/
function countSetsUser($user_id)
{
	global $db;
	
	$sql = "SELECT * FROM " . LIFT_TABLE . ", ". TRAINING_TABLE ." WHERE lifts.training_id = training.training_id AND user_id=". $user_id ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}
/** countSetsUser() From user END **/
/*******************************************************************
** countReps() Total
*******************************************************************/
function countReps()
{
	global $db;
	
	$sql = "SELECT SUM(rep) FROM " . LIFT_TABLE . "";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result)){
	$reps = $row['SUM(rep)'];
	echo $reps;
	}
}
/** countReps() END **/
/*******************************************************************
** countReps() From one user
*******************************************************************/
function countRepsUser($user_id)
{
	global $db;
	
	$sql = "SELECT SUM(rep), user_id, lifts.training_id, training.training_id FROM " . LIFT_TABLE . ", ". TRAINING_TABLE ." WHERE lifts.training_id = training.training_id AND user_id=". $user_id ." GROUP BY user_id";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result)){
	$reps = $row['SUM(rep)'];
	echo $reps;
	}
}
/** countReps() From one user END **/
/*******************************************************************
** countKgLifted()
*******************************************************************/
function countKgLifted()
{
	global $db;
	
	$sql = "SELECT SUM(rep * kg) AS sum_kg FROM " . LIFT_TABLE . "";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result))
	{
	$kglifted = round($row['sum_kg'], 2);
	echo $kglifted;
	}
}
/** countKgLifted() END **/
/*******************************************************************
** countLbsLifted()
*******************************************************************/
function countLbsLifted()
{
	global $db;
	
	$sql = "SELECT SUM(rep * kg) AS sum_kg FROM " . LIFT_TABLE . "";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result))
	{
	$lbslifted = round($row['sum_kg'], 2);
	echo round($lbslifted*2.20462262, 2);
	}
}
/** countLbsLifted() END **/

/*******************************************************************
** countTonLifted()
*******************************************************************/
function countTonLifted()
{
	global $db;
	
	$sql = "SELECT SUM((rep * kg)/1000) AS sum_ton FROM " . LIFT_TABLE . "";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result))
	{
	echo round($row['sum_ton'], 1);
	}
}
/** countTonLifted() END **/

/*******************************************************************
** countTimeHours()
*******************************************************************/
function countTimeHours()
{
	global $db;
	
	$sql = "SELECT SUM(timespent_hours), SUM(timespent_minutes) FROM " . TRAINING_TABLE . "";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result)){
	$hours = $row['SUM(timespent_hours)'];
	$minutes = $row['SUM(timespent_minutes)'];
	$minutesToHours = $minutes /60;
	//Rounds to nearest hour.
	$total =  round($hours + $minutesToHours, 0);
	echo $total;
	}
}
/** countTimeHours() END **/
/*******************************************************************
** countTimeHoursUser()
*******************************************************************/
function countTimeHoursUser($user_id)
{
	global $db;
	
	$sql = "SELECT SUM(timespent_hours), SUM(timespent_minutes) FROM " . TRAINING_TABLE . " WHERE user_id=". $user_id ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result)){
	$hours = $row['SUM(timespent_hours)'];
	$minutes = $row['SUM(timespent_minutes)'];
	$minutesToHours = $minutes /60;
	//Rounds to nearest hour.
	$total =  round($hours + $minutesToHours, 0);
	echo $total;
	}
}
/** countTimeHoursUser() END **/
/*******************************************************************
** Upload profile picture
*******************************************************************/
function updateAvatarPath($name, $user_id)
{
	global $db;
	global $CONFIG;
	
	$sql = "UPDATE " . USERS_TABLE . " SET user_avatarPath ='". $name ."' WHERE user_id =". $user_id ."";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
	return;	
	}
}
/** Upload profile picture END **/

function checkMsgFromcomments($user_id)
{
	global $db;
	
	$sql = "SELECT user_msg_from_comments FROM " . USERS_TABLE .
	" WHERE user_id='" . $user_id . "'";
	
	if(!$result = $db->sql_query($sql))
	{
		printError('SQL_ERROR', mysql_error($sql));
	}
	else
	{
		if($row = $db->sql_fetchrow($result))
		{
			return $row['user_msg_from_comments'];
		}
	}
	return $user_id;
}







/*******************************************************************
** countUsers()
*******************************************************************/
function countUsersToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT DISTINCT user_id FROM " . TRAINING_TABLE . " WHERE date > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}
/** countUsers() END **/
/*******************************************************************
** countTrainings()
*******************************************************************/
function countTrainingsToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT * FROM " . TRAINING_TABLE . " WHERE date > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}
/** countTrainings() END **/

/*******************************************************************
** countSetsUser() From user
*******************************************************************/
function countSetsToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT * FROM " . LIFT_TABLE . ", ". TRAINING_TABLE ." WHERE lifts.training_id = training.training_id AND training.date > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	else
	{
		return $db->sql_affectedrows();
	}
	return 0;
}
/** countSetsUser() From user END **/
/*******************************************************************
** countReps() From one user
*******************************************************************/
function countRepsToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT SUM(rep), user_id, lifts.training_id, training.training_id FROM " . LIFT_TABLE . ", ". TRAINING_TABLE ." WHERE lifts.training_id = training.training_id AND training.date > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result)){
	$reps = $row['SUM(rep)'];
	echo $reps;
	}
}
/** countReps() From one user END **/
/*******************************************************************
** countKgLifted()
*******************************************************************/
function countKgLiftedToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT SUM(rep * kg) AS sum_kg FROM " . LIFT_TABLE . ", ". TRAINING_TABLE ." WHERE lifts.training_id = training.training_id AND training.date > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result))
	{
	$kglifted = round($row['sum_kg'], 2);
	echo $kglifted;
	}
}
/** countKgLifted() END **/
/*******************************************************************
** countLbsLifted()
*******************************************************************/
function countLbsLiftedToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT SUM(rep * kg) AS sum_kg FROM " . LIFT_TABLE . ", ". TRAINING_TABLE ." WHERE lifts.training_id = training.training_id AND training.date > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result))
	{
	$lbslifted = round($row['sum_kg'], 2);
	echo round($lbslifted*2.20462262, 2);
	}
}
/** countLbsLifted() END **/

/*******************************************************************
** countTonLifted()
*******************************************************************/
function countTonLiftedToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT SUM((rep * kg)/1000) AS sum_ton FROM " . LIFT_TABLE . ", ". TRAINING_TABLE ." WHERE lifts.training_id = training.training_id AND training.date > ". $date ." ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result))
	{
	echo round($row['sum_ton'], 1);
	}
}
/** countTonLifted() END **/


/*******************************************************************
** countTimeHoursUser()
*******************************************************************/
function countTimeHoursToday()
{
	global $db;
	
	$time_now = time();
	$day = date('d', $time_now);
	$month = date('m', $time_now);
	$year = date('Y', $time_now);
	$date = mktime(date('H', 00), date('i', 00), date('s', 00), $month, $day, $year);
	
	$sql = "SELECT SUM(timespent_hours), SUM(timespent_minutes) FROM " . TRAINING_TABLE . " WHERE date > " . $date . " ";
	
	if(!$result = $db->sql_query($sql))
	{
		printError("SQL ERROR", mysql_error($sql));
	}
	while($row = mysql_fetch_array($result)){
	$hours = $row['SUM(timespent_hours)'];
	$minutes = $row['SUM(timespent_minutes)'];
	$minutesToHours = $minutes /60;
	//Rounds to nearest hour.
	$total =  round($hours + $minutesToHours, 0);
	echo $total;
	}
}
/** countTimeHoursUser() END **/

function is_follow_this_user($user_id){
	$MY_PROFILE = new User('id', $_SESSION['user_id']);
	$my_follow_user_array = explode(',', $MY_PROFILE->getUserFollowList());
	
	if(!in_array($user_id, $my_follow_user_array)){
		return false;
	}
	return true;
}

function ui_follow_this_user($user_id){
	if(!is_follow_this_user($user_id) ){
	    $ui = "<a href='index.php?action=profile&id=$user_id&following=add' >
				<div style='float: left; clear: right; padding-right: 5px;'><img src='img/stock_person.png' /></div>
				". translate('follow_this_user')."</a>";
	}else{  
	    $ui = "<a href='index.php?action=profile&id=$user_id&following=remove' >
				<div style='float: left; clear: right; padding-right: 5px;'><img src='img/stock_person.png' /></div>
				".translate('not_follow_this_user')."</a>";
	}
	return $ui;
}

function ui_aj_follow_this_user($user_id, $div_id){
	if($user_id == $_SESSION['user_id']){return '';}
	
	if(!is_follow_this_user($user_id) ){
	    $ui = "<a href='javascript:void(0);' onclick=\"follow_this_user({$user_id},'{$div_id}');\" >
				<img src='./img/stock_person.png' />
				<span class='follow_user' rel=\"{$div_id}\" >". translate('follow_this_user')."</span></a>";
	}else{  
	    $ui = "<a href='javascript:void(0);' onclick=\"follow_this_user({$user_id},'{$div_id}');\" >
				<img src='./img/stock_person.png' />
				<span class='follow_user' rel=\"{$div_id}\" >". translate('not_follow_this_user')."</span></a>";
	}
	return $ui;
}

function add_this_user_to_my_followList($user_id){
	$MY_PROFILE = new User('id', $_SESSION['user_id']);
	$my_follow_user_array = explode(',', $MY_PROFILE->getUserFollowList());
	array_push($my_follow_user_array, $user_id);
	
	$my_follow_user_array = array_filter($my_follow_user_array);
	$MY_PROFILE->setUserFollowList(implode(',', $my_follow_user_array));
	$MY_PROFILE->update();
	return;
}

function remove_this_user_to_my_followList($user_id){
	$MY_PROFILE = new User('id', $_SESSION['user_id']);
	$my_follow_user_array = explode(',', $MY_PROFILE->getUserFollowList());
	array_push($my_follow_user_array, $user_id);
	
	$my_follow_user_array = array_merge(array_diff($my_follow_user_array, array($user_id)));
	
	$MY_PROFILE->setUserFollowList(implode(',', $my_follow_user_array));
	$MY_PROFILE->update();
	return;
}

function who_am_i(){
	$MY_PROFILE = new User('id', $_SESSION['user_id']);
	if($MY_PROFILE->getRank() == 5)
	{	
		return "ADMIN";
	}
	if($MY_PROFILE->getRank() == 3)
	{	
		return "MOD";
	}
	if($MY_PROFILE->getRank() == 2)
	{	
		return "PRE";
	}	
	if($MY_PROFILE->getRank() == 1)
	{	
		return "USER";
	}
}

?>